<template>
    <div class="login-container">
        <el-card class="login-card" shadow="hover">
            <h2>用户登陆</h2>
            <el-form :model="formData" ref="form" size="small" :rules="rules" label-width="80px">
                <el-form-item label="用户名" prop="name">
                    <el-input v-model.trim="formData.name" autocomplete="off" clearable></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model.trim="formData.password" autocomplete="off" show-password
                        clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSubmit">登录</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>


<script lang="ts" scoped setup>

import type { LoginFromData, UserInfo } from '@/type/all-type';
import type { FormInstance, FormRules } from 'element-plus'
import { login } from '@/api/api'
import { userInfoState } from "@/stores/store"
import router from "@/router/index"


const formData: LoginFromData = reactive({
    name: "admin",
    password: "123"
})

const form = ref<FormInstance>()

const rules: FormRules = reactive({
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { message: '请输入3~6个字符', trigger: 'blur', min: 3, max: 6 }
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})


async function handleSubmit() {
    await form.value?.validate((isValid) => {
        if (isValid) {
            login(formData).then(res => {
                //登陆成功设置登陆状态并跳转首页
                let userInfo = res.data.data as UserInfo;
                userInfoState().setUser(userInfo)
                //跳转到主页
                router.push("/")
            }).catch((error: Error) => {
                ElMessage.error(error.message)
            })
        } else {
            ElMessage.error("表单校验未通过，请检查!")
        }
    })
}

</script>


<style scoped lang="scss">
.login-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;

    .login-card {
        width: 400px;
        text-align: center;

        h2 {
            margin-bottom: 20px;
        }
    }
}
</style>
  